//
//  XCCycleExtension.swift
//  XCCycleBanner
//
//  Created by edy on 2023/7/10.
//

import Foundation

class Block<T> {
    let f : T
    init(_ f: T) {
        self.f = f
    }
}

extension Timer {
    
    class func xc_scheduledTimer(
        withTimeInterval interval: TimeInterval,
        repeats: Bool,
        block: @escaping (Timer) -> Swift.Void) -> Timer {
        
        if #available(iOS 10.0, *) {
            
            return Timer.scheduledTimer(withTimeInterval: interval,
                                        repeats: repeats,
                                        block: block)
        }
        
        return Timer.scheduledTimer(timeInterval: interval,
                                    target: self,
                                    selector: #selector(xc_timerAction),
                                    userInfo: Block(block),
                                    repeats: repeats)
    }
    
    
    
    @objc class func xc_timerAction(_ sender: Timer) {
        if let block = sender.userInfo as? Block<(Timer) -> Swift.Void> {
            block.f(sender)
        }
    }
    
}


extension IndexPath {
    /// Reload the "+" operator
    static func + (left: IndexPath,
                   right: Int)
        -> IndexPath {
            return IndexPath.init(row: left.row + right,
                                  section: left.section)
    }
    
    /// Reload the "-" operator
    static func - (left: IndexPath,
                   right: Int)
        -> IndexPath {
            return IndexPath.init(row: left.row - right,
                                  section: left.section)
    }
}

extension UIView {
    
    // Determine if it's on screen
    func isShowingOnWindow() -> Bool {
        
        guard self.window != nil,
            isHidden != true,
            alpha > 0.01,
            superview != nil
            else {
                return false
        }
        
        // convert self to window's Rect
        var rect: CGRect = superview!.convert(frame, to: nil)
        
        // if size is CGrectZero
        if rect.isEmpty || rect.isNull || rect.size.equalTo(CGSize.zero) {
            return false
        }
        
        // set offset
        if let scorllView = self as? UIScrollView  {
            rect.origin.x += scorllView.contentOffset.x
            rect.origin.y += scorllView.contentOffset.y
        }

        // get the Rect that intersects self and window
        let screenRect: CGRect = UIScreen.main.bounds
        let intersectionRect: CGRect = rect.intersection(screenRect)
        if intersectionRect.isEmpty || intersectionRect.isNull {
            return false
        }
        
        return true
        
    }
}
